// utils/api.js - API请求工具类
const app = getApp()

/**
 * 封装wx.request
 * @param {Object} options 请求参数
 */
function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.baseUrl}${options.url}`,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data.data)
          } else {
            reject(new Error(res.data.msg || '请求失败'))
          }
        } else {
          reject(new Error(`HTTP ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * 显示加载提示
 * @param {String} title 提示文字
 */
function showLoading(title = '加载中...') {
  wx.showLoading({
    title: title,
    mask: true
  })
}

/**
 * 隐藏加载提示
 */
function hideLoading() {
  wx.hideLoading()
}

/**
 * 显示成功提示
 * @param {String} title 提示文字
 */
function showSuccess(title) {
  wx.showToast({
    title: title,
    icon: 'success',
    duration: 2000
  })
}

/**
 * 显示错误提示
 * @param {String} title 提示文字
 */
function showError(title) {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 2000
  })
}

/**
 * API接口定义
 */
const api = {
  // 根据券码搜索优惠券
  searchByCode: (ticketCode) => {
    return request({
      url: `/qdd/ticket/search/code/${ticketCode}`,
      method: 'GET'
    })
  },

  // 根据商品名称搜索优惠券
  searchByGoods: (goodsName, page = 1, limit = 20) => {
    return request({
      url: '/qdd/ticket/detail/goods',
      method: 'GET',
      data: {
        goodsName,
        page,
        limit
      }
    })
  },

  // 获取商家信息
  getMerchant: (merchantId) => {
    return request({
      url: `/qdd/merchant/${merchantId}`,
      method: 'GET'
    })
  },

  // 获取优惠券详情
  getTicket: (ticketId) => {
    return request({
      url: `/qdd/ticket/${ticketId}`,
      method: 'GET'
    })
  }
}

/**
 * 工具函数
 */
const utils = {
  // 格式化日期
  formatDate: (dateString) => {
    if (!dateString) return '无'
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 格式化日期时间
  formatDateTime: (dateString) => {
    if (!dateString) return '无'
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 检查券是否过期
  isExpired: (deadTime) => {
    if (!deadTime) return true
    const now = new Date()
    const expireDate = new Date(deadTime)
    return now > expireDate
  },

  // 验证券码格式
  validateTicketCode: (code) => {
    return /^\d{6}$/.test(code)
  },

  // 复制到剪贴板
  copyToClipboard: (text) => {
    return new Promise((resolve, reject) => {
      wx.setClipboardData({
        data: text.toString(),
        success: resolve,
        fail: reject
      })
    })
  },

  // 拨打电话
  makePhoneCall: (phoneNumber) => {
    return new Promise((resolve, reject) => {
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        success: resolve,
        fail: reject
      })
    })
  }
}

module.exports = {
  request,
  showLoading,
  hideLoading,
  showSuccess,
  showError,
  api,
  utils
}
